<?php


namespace app\miniProgram\controller;


use think\facade\Db;
use think\Request;

class Auth extends Base
{
    public function __construct(Request $request = null){
        parent::__construct($request);
        if(empty($this->userInfo)){
            $this->jump(["code"=>-1,"status"=>1,"message"=>""]);
        }
        if (!$this->checkAuth()){
            $this->jump(["code"=>2,"status"=>1,"message"=>""]);
        }
    }

    public function checkAuth()
    {
//        $unAuth=['other/getmaterial','other/getwarehouse','other/getywtype','other/getmaterialinfo',];
        $contrl=\request()->controller();
        $rUrl=strtolower(request()->pathinfo());
        if ($contrl=='Other'){
            return true;
        }
        $auth=$this->getAuth($this->userInfo['id']);
        if (in_array($rUrl,$auth)){
            return true;
        }
        return false;
    }


    public function getAuth($uid)
    {
        $position_id = Db::connect('company')->name('Admin')->where('id', $uid)->value('position_id');
        $groups = Db::connect('company')->name('PositionGroup')
            ->alias('a')
            ->join("AdminGroup g", "a.group_id=g.id", 'LEFT')
            ->where([['a.pid', '=', $position_id], ['g.status', '=', 1]])
            ->select()->toArray();
        //保存用户所属用户组设置的所有权限规则id
        $ids = [];
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);
        //读取所有权限规则
//        $rules_all = Db::name('AdminRule')->field('src')->select()->toArray();
        //读取用户组所有权限规则
        $rules = Db::connect('company')->name('AdminRule')->where('id', 'in', $ids)->field('src')->select()->toArray();
        //循环规则，判断结果。
//        $auth_list_all = [];
        $auth_list = [];
//        foreach ($rules_all as $rule_all) {
//            $auth_list_all[] = strtolower($rule_all['src']);
//        }
        foreach ($rules as $rule) {
            $str=strtolower($rule['src']);
            $strs=$str?explode('/',$str):[];
            $src='';
            if (!empty($strs)){
                unset($strs[0]);

            $auth_list[] = implode('/',$strs);
            }
        }
        return $auth_list;
    }
}